import 'package:dio/dio.dart';
import 'package:ioc_pay_app/common/NetCode.dart';

import 'ResultData.dart';

// ignore: non_constant_identifier_names
final String BASE_URL_RELEASE = "http:127.0.0.1:9500";

// dio  网络请求：
class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  Dio _dio;

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal({String baseUrl}) {
    if (null == _dio) {
      _dio = new Dio(
          new BaseOptions(baseUrl: BASE_URL_RELEASE, connectTimeout: 15000));
      // _dio.interceptors.add(new LogsInterceptors());
      // _dio.interceptors.add(new ResponseInterceptors());
    }
  }

  static HttpManager getInstance({String baseUrl}) {
    if (baseUrl == null) {
      return _instance._normal();
    } else {
      return _instance._baseUrl(baseUrl);
    }
  }

  //用于指定特定域名，比如cdn和kline首次的http请求
  HttpManager _baseUrl(String baseUrl) {
    if (_dio != null) {
      _dio.options.baseUrl = baseUrl;
    }
    return this;
  }

  //一般请求，默认域名
  HttpManager _normal() {
    if (_dio != null) {
      if (_dio.options.baseUrl != BASE_URL_RELEASE) {
        _dio.options.baseUrl = BASE_URL_RELEASE;
      }
    }
    return this;
  }

  //通用的GET请求
  get(url, params, {noTip = false}) async {
    Response response;
    try {
      response = await _dio.get(url, queryParameters: params);
    } on DioError catch (e) {
      return resultError(e);
    }

    if (response.data is DioError) {
      return resultError(response.data['code']);
    }
    return response.data;
  }

  //通用的POST请求
  post(url, params, {noTip = false}) async {
    Response response;
    try {
      response = await _dio.post(url, data: params);
    } on DioError catch (e) {
      return resultError(e);
    }
    if (response.data is DioError) {
      return resultError(response.data['code']);
    }
    return response.data;
  }

  // 请求异常返回：
  ResultData resultError(DioError e) {
    Response errorResponse;
    if (e.response != null) {
      errorResponse = e.response;
    } else {
      errorResponse = new Response(statusCode: 666);
    }
    if (e.type == DioErrorType.CONNECT_TIMEOUT ||
        e.type == DioErrorType.RECEIVE_TIMEOUT) {
      errorResponse.statusCode = NetCode.NETWORK_TIMEOUT;
    }
    return new ResultData(
        errorResponse.statusMessage, false, errorResponse.statusCode);
  }
}
